const express = require('express');
const router = express.Router();
const { generateToken, invalidateToken } = require('../utils/jwt');
const authMiddleware = require('../middleware/auth');
const DB = require('../config/mysql');
const bcrypt = require('bcryptjs');
const { 
  LOGIN_QUERY, 
  UPDATE_LAST_LOGIN, 
  CHECK_USERNAME, 
  REGISTER_USER,
  GET_ROLE_ID,
  GET_USER_INFO,
  GET_ALL_BANNERS,
  CREATE_BANNER,
  UPDATE_USER_ROLE
} = require('../sql/users.sql');
const ResponseCode = require('../utils/responseCode');
const { 
  GET_COURSES,
  GET_COURSE_DETAIL,
  CREATE_COURSE,
  ADD_COURSE_FEATURE,
  ADD_COURSE_TAG,
  ENROLL_COURSE
} = require('../sql/courses.sql');
const { GET_CATEGORIES, GET_COURSES_BY_CATEGORY } = require('../sql/categories.sql');
const { 
  GET_USER_NOTIFICATIONS, 
  GET_CHAT_HISTORY, 
  GET_ONLINE_CUSTOMER_SERVICE,
  GET_USER_MESSAGES,
  MARK_MESSAGE_READ,
  GET_UNREAD_COUNT,
  CREATE_CUSTOMER_SERVICE,
  INIT_CUSTOMER_SERVICE_STATUS,
  CHECK_CUSTOMER_SERVICE_USERNAME,
  GET_CONSULTATIONS,
  GET_CUSTOMER_SERVICE_DETAIL
} = require('../sql/messages.sql');
const redisClient = require('../config/redis');
const { JWT_SECRET, REDIS_EXPIRY } = require('../config/constants');

// 登录接口
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;

    if (!username || !password) {
      return res.json({
        code: ResponseCode.PARAM_ERROR,
        message: '用户名和密码为必填项'
      });
    }

    const user = await DB.findOne(LOGIN_QUERY, [username]);

    if (!user) {
      return res.json({
        code: ResponseCode.NO_DATA,
        message: '用户名或密码错误'
      });
    }

    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      return res.json({
        code: ResponseCode.NO_DATA,
        message: '用户名或密码错误'
      });
    }

    // 生成新token
    const token = generateToken(user.id);
    
    // 将旧token加入黑名单，保存新token
    await redisClient.get(`user_${user.id}`).then(async oldToken => {
      if (oldToken) {
        await redisClient.set(`bl_${oldToken}`, '1', {
          EX: REDIS_EXPIRY
        });
      }
      await redisClient.set(`user_${user.id}`, token, {
        EX: REDIS_EXPIRY
      });
    });

    // 更新最后登录时间和在线状态
    await DB.transaction(async (connection) => {
      await connection.execute(UPDATE_LAST_LOGIN, [new Date(), user.id]);
      
      if (user.role_name === 'customer_service') {
        await connection.execute(`
          INSERT INTO customer_service_status (user_id, status, last_active, session_count)
          VALUES (?, 'online', NOW(), 1)
          ON DUPLICATE KEY UPDATE 
            status = 'online', 
            last_active = NOW(),
            session_count = session_count + 1
        `, [user.id]);
      }
    });

    res.json({
      code: ResponseCode.SUCCESS,
      message: '登录成功',
      data: { token }
    });

  } catch (error) {
    console.error('登录错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '登录失败，请稍后重试'
    });
  }
});

// 退出登录接口
router.post('/logout', authMiddleware, async (req, res) => {
  try {
    const userId = req.user.userId;
    const authHeader = req.headers.authorization;
    // 修改 token 提取逻辑，支持直接传递 token
    const token = authHeader && authHeader.startsWith('Bearer ') 
      ? authHeader.slice(7)  // Bearer token 格式
      : authHeader;          // 直接传递 token
    
    console.log('收到的token:', token);

    if (!token) {
      return res.json({
        code: ResponseCode.PARAM_ERROR,
        message: '无效的token'
      });
    }

    try {
      // 先检查当前用户的token是否存在
      const currentToken = await redisClient.get(`user_${userId}`);
      console.log('Redis中的token:', currentToken);
      
      // 如果存在token，则进行删除操作
      if (currentToken) {
        // 将token加入黑名单
        await redisClient.set(`bl_${token}`, '1', {
          EX: REDIS_EXPIRY
        });
        // 删除用户token记录
        await redisClient.del(`user_${userId}`);
      }

      // 如果是客服，更新状态为离线
      const [userRole] = await DB.query(`
        SELECT r.role_name 
        FROM users u 
        JOIN user_roles r ON u.role_id = r.id 
        WHERE u.id = ?
      `, [userId]);

      if (userRole && userRole.role_name === 'customer_service') {
        await DB.query(`
          UPDATE customer_service_status 
          SET 
            session_count = GREATEST(0, session_count - 1),
            status = CASE 
              WHEN session_count <= 1 THEN 'offline'
              ELSE status 
            END,
            last_active = NOW()
          WHERE user_id = ?
        `, [userId]);
      }

      res.json({
        code: ResponseCode.SUCCESS,
        message: '退出成功'
      });
    } catch (error) {
      console.error('Redis操作错误:', error);
      throw error;
    }
  } catch (error) {
    console.error('退出登录错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '退出失败'
    });
  }
});

// 测试认证的路由
router.get('/protected', authMiddleware, (req, res) => {
  res.json({ message: '认证成功', userId: req.user.userId });
});

// 注册接口
router.post('/register', async (req, res) => {
  try {
    const {
      username,
      password,
      role_name = 'student', // 默认注册为学生
      real_name,
      phone,
      email,
      gender,
      birth_date
    } = req.body;

    if (!username || !password) {
      return res.json({
        code: ResponseCode.PARAM_ERROR,
        message: '用户名和密码为必填项'
      });
    }

    const existingUser = await DB.findOne(CHECK_USERNAME, [username]);
    if (existingUser) {
      return res.json({
        code: ResponseCode.NO_DATA,
        message: '用户名已存在'
      });
    }

    // 获取角色ID
    const roleResult = await DB.findOne(GET_ROLE_ID, [role_name]);
    if (!roleResult) {
      return res.json({
        code: ResponseCode.NO_DATA,
        message: '无效的角色类型'
      });
    }

    // 开启事务
    await DB.transaction(async (connection) => {
      // 密码加密
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(password, salt);

      // 创建用户
      await connection.execute(REGISTER_USER, [
        username,
        hashedPassword,
        roleResult.id,
        real_name || null,
        phone || null,
        email || null,
        gender || null,
        birth_date || null
      ]);

      // 如果是学生，创建学生档案
      if (role_name === 'student') {
        await connection.execute(require('../sql/students.sql').CREATE_STUDENT_PROFILE, [
          userId,
          null, // emergency_contact
          null, // emergency_phone
          'beginner', // default dance_level
          null  // health_note
        ]);
      }

      // 如果是教师，创建教师档案
      if (role_name === 'teacher') {
        await connection.execute(require('../sql/teachers.sql').CREATE_TEACHER_PROFILE, [
          userId,
          null, // specialties
          0,    // experience_years
          null, // certification
          null, // introduction
          null  // achievement
        ]);
      }
    });

    res.json({
      code: ResponseCode.SUCCESS,
      message: '注册成功'
    });

  } catch (error) {
    console.error('注册错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '注册失败，请稍后重试'
    });
  }
});

// 获取用户信息接口
router.get('/user/info', authMiddleware, async (req, res) => {
  try {
    const userId = req.user.userId;
    const userInfo = await DB.findOne(GET_USER_INFO, [userId]);

    if (!userInfo) {
      return res.json({
        code: ResponseCode.NO_DATA,
        message: '用户不存在或已被禁用'
      });
    }

    // 处理 profile_info
    if (userInfo.profile_info) {
      try {
        // 如果已经是对象，就不需要解析
        if (typeof userInfo.profile_info === 'string') {
          userInfo.profile_info = JSON.parse(userInfo.profile_info);
        }
      } catch (e) {
        console.error('解析 profile_info 失败:', e);
        userInfo.profile_info = {};
      }
    } else {
      userInfo.profile_info = {};
    }

    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: userInfo
    });

  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取用户信息失败，请稍后重试'
    });
  }
});

// 获取所有轮播图（包括未启用的，需要管理员权限）
router.get('/admin/banners', authMiddleware, async (req, res) => {
  try {
    const banners = await DB.query(GET_ALL_BANNERS);
    
    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: banners
    });
  } catch (error) {
    console.error('获取轮播图错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取轮播图失败，请稍后重试'
    });
  }
});

// 创建轮播图（需要管理员权限）
router.post('/admin/banners', authMiddleware, async (req, res) => {
  try {
    const {
      title,
      image_url,
      route_path,
      sort_order,
      status,
      start_time,
      end_time,
      description
    } = req.body;

    await DB.query(CREATE_BANNER, [
      title,
      image_url,
      route_path,
      sort_order,
      status,
      start_time,
      end_time,
      description
    ]);

    res.json({
      code: ResponseCode.SUCCESS,
      message: '创建成功'
    });
  } catch (error) {
    console.error('创建轮播图错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '创建轮播图失败，请稍后重试'
    });
  }
});

// 获取所有分类
router.get('/categories', async (req, res) => {
  try {
    const categories = await DB.query(GET_CATEGORIES);
    
    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: categories
    });
  } catch (error) {
    console.error('获取分类列表错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取分类列表失败'
    });
  }
});

// 修改课程列表接口，支持分类过滤
router.get('/courses', authMiddleware, async (req, res) => {
  try {
    const { categoryId } = req.query;
    let courses;
    
    if (categoryId) {
      // 获取指定分类的课程
      courses = await DB.query(GET_COURSES_BY_CATEGORY, [categoryId]);
    } else {
      // 获取所有课程
      courses = await DB.query(GET_COURSES);
    }
    
    // 处理每个课程的数据
    const formattedCourses = courses.map(course => ({
      ...course,
      tags: course.tags ? course.tags.split(',') : [],
      category_ids: course.category_ids ? course.category_ids.split(',').map(Number) : [],
      category_names: course.category_names ? course.category_names.split(',') : [],
      enrolled_students: parseInt(course.enrolled_students || 0),
      price: parseFloat(course.price),
      original_price: parseFloat(course.original_price)
    }));

    if (!formattedCourses.length) {
      return res.json({
        code: ResponseCode.NO_DATA,
        message: '暂无课程数据'
      });
    }

    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: formattedCourses
    });
  } catch (error) {
    console.error('获取课程列表错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取课程列表失败，请稍后重试'
    });
  }
});

// 获取课程详情
router.get('/courses/:id', authMiddleware, async (req, res) => {
  try {
    const courseId = req.params.id;
    const [course] = await DB.query(GET_COURSE_DETAIL, [courseId]);

    if (!course) {
      return res.json({
        code: ResponseCode.NO_DATA,
        message: '课程不存在或已下架'
      });
    }

    // 处理课程数据
    const formattedCourse = {
      ...course,
      tags: course.tags ? course.tags.split(',') : [],
      features: course.features ? course.features.split(',') : [],
      enrolled_students: parseInt(course.enrolled_students || 0),
      price: parseFloat(course.price),
      original_price: parseFloat(course.original_price)
    };

    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: formattedCourse
    });
  } catch (error) {
    console.error('获取课程详情错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取课程详情失败，请稍后重试'
    });
  }
});

// 创建课程（需要教师权限）
router.post('/courses', authMiddleware, async (req, res) => {
  try {
    const {
      title,
      short_desc,
      description,
      image_url,
      level,
      price,
      original_price,
      duration,
      max_students,
      schedule,
      features = [],
      tags = []
    } = req.body;

    // 验证必填字段
    if (!title || !price || !duration) {
      return res.json({
        code: ResponseCode.PARAM_ERROR,
        message: '课程标题、价格和课时为必填项'
      });
    }

    // 开启事务
    await DB.transaction(async (connection) => {
      // 创建课程
      const [result] = await connection.execute(CREATE_COURSE, [
        title,
        short_desc,
        description,
        image_url,
        req.user.userId, // 当前登录的教师ID
        level,
        price,
        original_price,
        duration,
        max_students,
        schedule,
        'published'
      ]);

      const courseId = result.insertId;

      // 添加课程特点
      for (const feature of features) {
        await connection.execute(ADD_COURSE_FEATURE, [courseId, feature]);
      }

      // 添加课程标签
      for (const tagId of tags) {
        await connection.execute(ADD_COURSE_TAG, [courseId, tagId]);
      }
    });

    res.json({
      code: ResponseCode.SUCCESS,
      message: '创建成功'
    });
  } catch (error) {
    console.error('创建课程错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '创建课程失败，请稍后重试'
    });
  }
});

// 获取用户通知列表
router.get('/notifications', authMiddleware, async (req, res) => {
  try {
    const userId = req.user.userId;
    const notifications = await DB.query(GET_USER_NOTIFICATIONS, [userId, userId, userId]);

    // 格式化通知数据
    const formattedNotifications = notifications.map(notification => ({
      ...notification,
      is_read: !!notification.is_read,
      created_at: new Date(notification.created_at).toISOString(),
      read_at: notification.read_at ? new Date(notification.read_at).toISOString() : null
    }));

    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: formattedNotifications
    });
  } catch (error) {
    console.error('获取通知列表错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取通知列表失败'
    });
  }
});

// 标记通知为已读
router.post('/notifications/:id/read', authMiddleware, async (req, res) => {
  try {
    const userId = req.user.userId;
    const notificationId = req.params.id;

    await DB.query(`
      INSERT INTO user_notifications (user_id, notification_id, is_read, read_at)
      VALUES (?, ?, 1, NOW())
      ON DUPLICATE KEY UPDATE is_read = 1, read_at = NOW()
    `, [userId, notificationId]);

    res.json({
      code: ResponseCode.SUCCESS,
      message: '标记成功'
    });
  } catch (error) {
    console.error('标记通知已读错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '标记失败'
    });
  }
});

// 获取在线客服列表
router.get('/customer-service', authMiddleware, async (req, res) => {
  try {
    const customerService = await DB.query(GET_ONLINE_CUSTOMER_SERVICE);
    
    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: customerService
    });
  } catch (error) {
    console.error('获取客服列表错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取客服列表失败'
    });
  }
});

// 获取聊天记录
router.get('/chat-history', authMiddleware, async (req, res) => {
  try {
    const userId = req.user.userId;
    const targetId = parseInt(req.query.targetId);
    const limit = parseInt(req.query.limit) || 50;

    // 确保 targetId 存在
    if (!targetId) {
      return res.json({
        code: ResponseCode.PARAM_ERROR,
        message: '目标用户ID不能为空'
      });
    }

    // 修改查询方式，将 LIMIT 参数放在最后
    const messages = await DB.query(`
      SELECT 
        m.*,
        u1.username as from_username,
        u2.username as to_username
      FROM chat_messages m
      JOIN users u1 ON m.from_user_id = u1.id
      JOIN users u2 ON m.to_user_id = u2.id
      WHERE (m.from_user_id = ? AND m.to_user_id = ?)
        OR (m.from_user_id = ? AND m.to_user_id = ?)
      ORDER BY m.created_at DESC
      LIMIT ${limit}
    `, [
      userId, 
      targetId,
      targetId, 
      userId
    ]);

    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: messages
    });
  } catch (error) {
    console.error('获取聊天记录错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取聊天记录失败'
    });
  }
});

// 获取消息列表
router.get('/messages', authMiddleware, async (req, res) => {
  try {
    const userId = req.user.userId;
    const messages = await DB.query(GET_USER_MESSAGES, [userId]);

    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: messages
    });
  } catch (error) {
    console.error('获取消息列表错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取消息列表失败'
    });
  }
});

// 标记消息为已读
router.post('/messages/:id/read', authMiddleware, async (req, res) => {
  try {
    const userId = req.user.userId;
    const messageId = req.params.id;

    await DB.query(MARK_MESSAGE_READ, [messageId, userId]);

    res.json({
      code: ResponseCode.SUCCESS,
      message: '标记成功'
    });
  } catch (error) {
    console.error('标记消息已读错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '标记失败'
    });
  }
});

// 获取未读消息数量
router.get('/messages/unread/count', authMiddleware, async (req, res) => {
  try {
    const userId = req.user.userId;
    const [result] = await DB.query(GET_UNREAD_COUNT, [userId]);

    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: {
        count: result.count
      }
    });
  } catch (error) {
    console.error('获取未读消息数量错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取未读消息数量失败'
    });
  }
});

// 发送系统通知
router.post('/notifications/send', authMiddleware, async (req, res) => {
  try {
    const { title, content, type, targetType = 'all', targetId = null } = req.body;
    
    // 检查权限（只允许管理员发送系统通知）
    const isAdmin = await DB.findOne(`
      SELECT 1 FROM users u 
      JOIN user_roles r ON u.role_id = r.id 
      WHERE u.id = ? AND r.role_name = 'admin'
    `, [req.user.userId]);

    if (!isAdmin) {
      return res.json({
        code: ResponseCode.AUTH_ERROR,
        message: '没有权限发送系统通知'
      });
    }

    // 创建通知
    const result = await DB.query(`
      INSERT INTO notifications (
        title,
        content,
        type,
        target_type,
        target_id
      ) VALUES (?, ?, ?, ?, ?)
    `, [title, content, type, targetType, targetId]);

    // 通过 WebSocket 推送给在线用户
    const notification = {
      id: result.insertId,
      title,
      content,
      type,
      created_at: new Date().toISOString()
    };

    // 广播通知
    global.wss.broadcast({
      type: 'notification',
      data: notification
    }, (userId) => {
      // 根据 targetType 过滤接收用户
      if (targetType === 'all') return true;
      if (targetId && targetId === userId) return true;
      return false;
    });

    res.json({
      code: ResponseCode.SUCCESS,
      message: '发送成功'
    });
  } catch (error) {
    console.error('发送通知错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '发送通知失败'
    });
  }
});

// 添加客服账号（仅管理员）
router.post('/customer-service/create', authMiddleware, async (req, res) => {
  try {
    // 检查是否是管理员
    const isAdmin = await DB.findOne(`
      SELECT 1 FROM users u 
      JOIN user_roles r ON u.role_id = r.id 
      WHERE u.id = ? AND r.role_name = 'admin'
    `, [req.user.userId]);

    if (!isAdmin) {
      return res.json({
        code: ResponseCode.AUTH_ERROR,
        message: '没有权限创建客服账号'
      });
    }

    const { 
      username,        // 登录账号，如 "cs001"
      password,        // 登录密码
      real_name,      // 真实姓名，如 "李明"
      service_name,   // 客服显示名称，如 "客服小李"
      phone, 
      email 
    } = req.body;

    // 检查必填字段
    if (!username || !password || !real_name || !service_name) {
      return res.json({
        code: ResponseCode.PARAM_ERROR,
        message: '登录账号、密码、真实姓名和客服显示名称为必填项'
      });
    }

    // 检查用户名是否已存在
    const existingUser = await DB.findOne(CHECK_CUSTOMER_SERVICE_USERNAME, [username]);
    if (existingUser) {
      return res.json({
        code: ResponseCode.PARAM_ERROR,
        message: '用户名已存在'
      });
    }

    // 开启事务
    await DB.transaction(async (connection) => {
      // 密码加密
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(password, salt);

      // 创建客服用户
      const result = await connection.execute(CREATE_CUSTOMER_SERVICE, [
        username,
        hashedPassword,
        real_name,
        service_name,
        phone || null,
        email || null
      ]);

      // 初始化客服状态
      await connection.execute(INIT_CUSTOMER_SERVICE_STATUS, [result.insertId]);
    });

    res.json({
      code: ResponseCode.SUCCESS,
      message: '创建客服账号成功'
    });

  } catch (error) {
    console.error('创建客服账号错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '创建客服账号失败'
    });
  }
});

// 修改用户角色（仅管理员）
router.post('/users/:id/role', authMiddleware, async (req, res) => {
  try {
    // 检查是否是管理员
    const isAdmin = await DB.findOne(`
      SELECT 1 FROM users u 
      JOIN user_roles r ON u.role_id = r.id 
      WHERE u.id = ? AND r.role_name = 'admin'
    `, [req.user.userId]);

    if (!isAdmin) {
      return res.json({
        code: ResponseCode.AUTH_ERROR,
        message: '没有权限修改用户角色'
      });
    }

    const userId = req.params.id;
    const { role_name } = req.body;

    // 验证角色是否有效
    const validRoles = ['admin', 'teacher', 'student', 'customer_service'];
    if (!validRoles.includes(role_name)) {
      return res.json({
        code: ResponseCode.PARAM_ERROR,
        message: '无效的角色类型'
      });
    }

    await DB.query(UPDATE_USER_ROLE, [role_name, userId]);

    // 如果设置为客服，初始化客服状态
    if (role_name === 'customer_service') {
      await DB.query(INIT_CUSTOMER_SERVICE_STATUS, [userId]);
    }

    res.json({
      code: ResponseCode.SUCCESS,
      message: '修改角色成功'
    });

  } catch (error) {
    console.error('修改用户角色错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '修改用户角色失败'
    });
  }
});

// 获取与客服的聊天记录（用户使用）
router.get('/consultations', authMiddleware, async (req, res) => {
  try {
    const userId = req.user.userId; // 当前用户ID
    // 打印调试信息
    console.log('User ID:', userId);
    // 查询与该用户相关的所有聊天记录，返回聊天对象的ID和其他信息
    const messages = await DB.query(`
      SELECT 
        m.content,
        m.created_at,
        CASE 
          WHEN m.from_user_id = ? THEN u2.avatar_url
          ELSE u1.avatar_url
        END AS avatar_url,
        CASE 
          WHEN m.from_user_id = ? THEN u2.username
          ELSE u1.username
        END AS username,
        CASE 
          WHEN m.from_user_id = ? THEN m.to_user_id
          ELSE m.from_user_id
        END AS chat_partner_id
      FROM chat_messages m
      JOIN users u1 ON m.from_user_id = u1.id
      JOIN users u2 ON m.to_user_id = u2.id
      WHERE m.from_user_id = ? OR m.to_user_id = ?
      ORDER BY m.created_at DESC
    `, [userId, userId, userId, userId, userId]);

    // 处理消息数据，确保只添加需要的字段
    const responseData = messages.map(message => ({
      chat_partner_id: message.chat_partner_id, // 聊天对象的ID
      username: message.username, // 聊天对象的昵称
      avatar_url: message.avatar_url, // 聊天对象的头像
      content: message.content, // 聊天内容
      created_at: message.created_at // 聊天时间
    }));

    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: responseData
    });
  } catch (error) {
    console.error('获取咨询记录错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取咨询记录失败'
    });
  }
});

// 获取客服详细信息
router.get('/customer-service/:id', authMiddleware, async (req, res) => {
  try {
    const csId = req.params.id;
    
    const customerService = await DB.findOne(GET_CUSTOMER_SERVICE_DETAIL, [csId]);
    
    if (!customerService) {
      return res.json({
        code: ResponseCode.NO_DATA,
        message: '客服不存在'
      });
    }

    // 获取最近的服务记录，修改 SQL 查询
    const recentChats = await DB.query(`
      SELECT 
        u.username as user_name,
        u.avatar_url as user_avatar,
        MAX(c.created_at) as last_time,
        MAX(c.content) as last_message,
        COUNT(*) as message_count,
        SUM(CASE WHEN c.is_read = 0 THEN 1 ELSE 0 END) as unread_count
      FROM chat_messages c
      JOIN users u ON c.from_user_id = u.id
      WHERE c.to_user_id = ?
      GROUP BY 
        c.from_user_id,
        u.username,
        u.avatar_url
      ORDER BY last_time DESC
      LIMIT 5
    `, [csId]);

    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: {
        ...customerService,
        recent_chats: recentChats
      }
    });

  } catch (error) {
    console.error('获取客服详情错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取客服详情失败'
    });
  }
});

// 获取与特定用户的聊天记录（客服使用）
router.get('/user-consultations/:customerId', authMiddleware, async (req, res) => {
  try {
    const customerId = parseInt(req.params.customerId); // 从路径参数中获取客户ID
    const userId = req.user.userId; // 当前客服ID
    // 确保 customerId 存在
    if (!customerId) {
      return res.status(400).json({
        code: ResponseCode.PARAM_ERROR,
        message: '客户ID不能为空'
      });
    }

    // 查询客户信息
    const customerInfo = await DB.query(`
      SELECT 
        u.id AS customer_id,
        u.username,
        u.avatar_url,
        u.phone,
        u.email,
        cs.status
      FROM users u
      LEFT JOIN customer_service_status cs ON u.id = cs.user_id
      WHERE u.id = ?
    `, [customerId]);

    // 检查客户是否存在
    if (customerInfo.length === 0) {
      return res.status(404).json({
        code: ResponseCode.NOT_FOUND,
        message: '客户未找到'
      });
    }

    // 返回客户信息
    const responseData = {
      customer_id: customerInfo[0].customer_id,
      username: customerInfo[0].username,
      avatar_url: customerInfo[0].avatar_url,
      phone: customerInfo[0].phone,
      email: customerInfo[0].email,
      service_status: customerInfo[0].service_status,
      service_name: customerInfo[0].service_name
    };

    res.json({
      code: ResponseCode.SUCCESS,
      message: '获取成功',
      data: responseData
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '获取用户信息失败'
    });
  }
});

// 用户注册接口
router.post('/user/register', async (req, res) => {
  try {
    const { username, password, phone, email, role } = req.body;

    // 检查必填字段
    if (!username || !password || !phone || !email || !role) {
      return res.status(400).json({
        code: ResponseCode.PARAM_ERROR,
        message: '所有字段都是必填的'
      });
    }

    // 检查角色是否有效
    const roleIdResult = await DB.query(GET_ROLE_ID, [role]);
    if (roleIdResult.length === 0) {
      return res.status(400).json({
        code: ResponseCode.PARAM_ERROR,
        message: '无效的角色'
      });
    }
    const roleId = roleIdResult[0].id;

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 插入新用户到数据库
    const result = await DB.query(`
      INSERT INTO users (username, password, phone, email, role_id, status)
      VALUES (?, ?, ?, ?, ?, 'active')
    `, [username, hashedPassword, phone, email, roleId]);

    res.json({
      code: ResponseCode.SUCCESS,
      message: '注册成功',
      data: {
        userId: result.insertId, // 返回新用户的ID
        username,
        phone,
        email,
        role
      }
    });
  } catch (error) {
    console.error('用户注册错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '注册失败'
    });
  }
});

module.exports = router; 